package com.ecsolutions.controller;

import com.ecsolutions.common.ObjectHelp;
import com.ecsolutions.entity.*;
import com.ecsolutions.service.*;
import com.ecsolutions.soaClient.TransferClient;
import com.ecsolutions.soaClient.WorkFlowServiceManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ta.workflow.wcf.WorkflowStub;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/7/31.
 */
@Controller
public class Examination_Controller {
    @Autowired
    private AmountDeal_Service amountDeal_service;
    @Autowired
    private TransferClient client;
    @Autowired
    private ApplyInfo_Service applyInfo_service;
    @Autowired
    private  ExaminationService examinationService;
    @Autowired
    private ApplySerial_Service applySerial_service;
    @Autowired
    private WorkFlowServiceManager workFlowServiceManager;

    @Autowired
    private Facility_Service facility_service;
    @Autowired
    private Utilization_Service utilization_service;

    public ApplyInfo_Service getApplyInfo_Service() {
        return applyInfo_service;
    }

    public ExaminationService getExaminationService(){return examinationService;}

    @GetMapping("/examination")
    public String getExaminationPage(Model model,@RequestParam("loanid") String loanid,@RequestParam("userid") String userid) {//userid为操作人员id
        model.addAttribute("branch", applyInfo_service.getBranch(userid));//登录用户所在银行
        model.addAttribute("puId", examinationService.getPuid(loanid));//自动生成的序号
        model.addAttribute("applyInfo_info", applyInfo_service.getPopupInfo(loanid));//申请工作流表
        model.addAttribute("users_info", examinationService.getUsersInfo());//参会委员获取
        model.addAttribute("examination", new Examination());//需要提交的审核结果表信息
        model.addAttribute("loanid", loanid);
        model.addAttribute("userid", userid);
        return "examination";
    }

    @PostMapping("/examination")
    public String PostExaminationPage(@ModelAttribute Examination examination,Model model, @RequestParam("loanid") String loanid, @RequestParam("userid") String userid) {//userid为操作人员id
        //1：更新状况表MicroCreditAuditLog
        String taskId = applySerial_service.getTaskId(loanid, userid);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        boolean state1 = applySerial_service.insertMicroCreditAuditLogRecord(taskId,
                applySerial_service.getCustcodebyBPM_NO(loanid),
                loanid,
                amountDeal_service.dealWithMoneyAmount(applySerial_service.getAuditNo(), 3, 0),
                simpleDateFormat.format(date),
                applyInfo_service.getBranch(userid),
                examination.getWorkItemTitle(),
                examination.getAuditContext(),
                examination.getActionUserName(),
                examination.getResult()
        );
        if (state1)
            System.out.println("-----1完成-----");
        else
            System.out.println("-----1失败-----");
        //2：更新工作流状态表LoanRouteHistory
        String resultText = "default";
        if (examination.getResult().equals("1"))
            resultText = "退回再议";
        else if (examination.getResult().equals("2")) {
            resultText = "拒绝";
        } else if (examination.getResult().equals("3")) {
            resultText = "通过";
        } else if (examination.getResult().equals("4")) {
            resultText = "额度审核通过";
        } else if (examination.getResult().equals("5")) {
            resultText = "额度审核退回";
        }
        System.out.println(taskId);
        boolean state2 = applySerial_service.startOrUpdateWorkFlow(userid, loanid, "审贷会审批", resultText, taskId);
        if (state2)
            System.out.println("-----2完成-----");
        else
            System.out.println("-----2失败-----");
        System.out.println(examination.getResult()+"----------------");
        //3:根据条件判断调用SOA接口或更新表
        if (examination.getResult().trim().equals("3")) {
            //审批通过
            System.out.println(examination.getResult()+"----------------");
            //此处判断tblusers. Businesamoun >= 本次授信中的额度金额
            //数据不全，暂不予判断，默认通过

            //根据custcode以及BPM_NO更新授信表AppFlag为Y
            String custcode = applySerial_service.getCustcodebyBPM_NO(loanid);
            if (custcode != null)
                applySerial_service.updateAppFlagWithBPM_NO(custcode, loanid);

            //调用SOA以下接口
            //	C00003  LORCIFMW   更新CIF
            //	C00004  LORCLSMW   更新CLS
            //	C00005  LORLOSMW   更新贷款信息

            String result_C00003 = "";
            String result_C00004 = "";
            String result_C00005 = "";
            //C000003 start
            System.out.println("call TransferClient.transfer(UpdateEnCIFTx/UpdateCuCIFTx)");
            String mess = "";
            String recieveMsg = "";
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("QCUSTCD", examinationService.getCustcod(loanid) + "");
                jsonObject.put("QOVERWR", "Y");
                jsonObject.put("QDITION", "");
                jsonObject.put("QCNT", "1");//CIF总记录数
                String personalflag = examinationService.getCustomerType(examinationService.getCustcod(loanid));
                if (personalflag.equals("N")) {//企业
                    Acpy_Enterprise_Entity entity = examinationService.getEnterprise(examinationService.getCustcod(loanid));
                    entity.setPersonalFlag("E");
                    //补满金额位数
                    entity.setInvestmentAmount(amountDeal_service.dealWithMoneyAmount(entity.getInvestmentAmount(), 12, 3));
                    entity.setCustTypeAndBorrowerCharacteristics(entity.getCustType() + entity.getBorrowerCharacteristics());
                    //QMSG
                    JSONArray jsonArray = JSONArray.fromObject(entity);
                    jsonObject.put("QMSG", jsonArray.toString());
                    mess = ObjectHelp.InitTransferData2("UpdateEnCIFTx", jsonObject.toString());
                } else if (personalflag.equals("Y")) {//个人
                    Acpy_Customer_Entity entity = examinationService.getPersonal(examinationService.getCustcod(loanid));
                    entity.setPersonalflag("P");
                    entity.setInvestmentAmount(amountDeal_service.dealWithMoneyAmount(entity.getInvestmentAmount(), 12, 3));
                    if (null != entity.getApplyDate())
                        entity.setApplyDate(entity.getApplyDate().replace("-", ""));
//                entity.setForeign("Y");
                    JSONArray jsonArray = JSONArray.fromObject(entity);
                    jsonObject.put("QMSG", jsonArray.toString());//报文
                    mess = ObjectHelp.InitTransferData2("UpdateCuCIFTx", jsonObject.toString());
                }
                System.out.println("sendMsg----------"+mess);
                recieveMsg = client.transfer(mess);
                System.out.println("recieveMsg----------"+recieveMsg);
                if (recieveMsg != null && recieveMsg.length() > 0) {
                    JSONObject reply_C00003 = JSONObject.fromObject(recieveMsg);
                    result_C00003 = reply_C00003.getString("PRSPMSG");
                    System.out.println("result_C00003------"+result_C00003);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //c000003 end
            //c000004 数据不全，暂时不用
            String custcod = examinationService.getCustcod(loanid);
//            System.out.println(custcod);
//            JSONObject ExaminationJSON = new JSONObject();
//            ExaminationJSON.put("QCUSTCD", custcod);
//            ExaminationJSON.put("QOVERWR", "Y");
//            ExaminationJSON.put("QDITION", "");
//            ExaminationJSON.put("QCNT", "1");
//            System.out.println("call TransferClient.transfer(UpdateCuCLSTx)");
//            String prtncod = "";
//            try {
//                String mess_C00004 = ObjectHelp.InitTransferData("UpdateCuCLSTx", ExaminationJSON);
////        System.out.println("****customer_code:"+client.transfer(mess));
//                String recieveMsg_C00004 = client.transfer(mess_C00004);
//                System.out.println(recieveMsg_C00004);
//                if (recieveMsg_C00004 != null || recieveMsg_C00004.length() > 0) {
//                    JSONObject recieveJson = JSONObject.fromObject(recieveMsg_C00004);
//                    prtncod = recieveJson.getString("PRTNCOD");
//                    if (prtncod.equals("0000")) {
//                        System.out.println("get ExaminationInformation success");
//                    } else {
//                        System.out.println("Cannot get ExaminationInformation From Soa");
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            result_C00004="0000";
            //C00004  end
            //C00005  start
            //C00005  参数不清楚，暂时注释
//            String bmp_no = loanid;
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//            Test_Entity test_entity = new Test_Entity();
//            Facility_Entity facility_entity = utilization_service.getFacilityInfo(bmp_no);
//            //klasjdflkasjdlkf
//            Utilization_Entity utilization_entity = utilization_service.getUtilizationinfo(bmp_no);
//            String lineamt = String.valueOf(utilization_entity.getLineamt());
//            test_entity.setLineamt(lineamt + "00");//额度金额
//
//            String prodtype = facility_entity.getProdtype();
//            test_entity.setProdtype(prodtype);//贷款类型
//            String schetype = utilization_entity.getSchetype();
//            test_entity.setSchetype(schetype);//方案类型
//            test_entity.setBankid("1Y1");//行号ID
//            test_entity.setCustcod(custcod);//客户号
//            String loanref = utilization_entity.getLoanref();
//            test_entity.setLoanref(loanref);//贷款编号
//            String drawdate = sdf.format(utilization_entity.getDrawdate());
//            test_entity.setDrawdate(drawdate);//放款日期
//            String drawccy = utilization_entity.getDrawccy();
//            test_entity.setDrawccy(drawccy);//放款币种
//            String drawamt = String.valueOf(utilization_entity.getDrawamt());
//            test_entity.setDrawamt(drawamt + "00");//放款金额
//            String tenor = utilization_entity.getTenor();
//            test_entity.setTenor(tenor);//期数
//            String lineno = utilization_entity.getLineno();
//            test_entity.setLineno(lineno);//额度号
//            String avliamt = String.valueOf(utilization_entity.getAvliamt());
//            test_entity.setAvliamt(avliamt + "00");//可用金额
//            String schemarate = utilization_entity.getSchemarate();
//            int length = schemarate.length() - schemarate.indexOf(".") - 1;
//            if (length < 7) {
//                for (int i = 1; i <= 7 - length; i++) {
//                    schemarate = schemarate + "0";
//                }
//            }
//            test_entity.setSchemarate(schemarate);//利率-调整后年利率4.075 40.75
//            String overdurate = utilization_entity.getOverdurate();
//            int length1 = overdurate.length() - overdurate.indexOf(".") - 1;
//            if (length < 7) {
//                for (int i = 1; i <= 7 - length; i++) {
//                    overdurate = overdurate + "0";
//                }
//            }
//            test_entity.setOvdayinrate(overdurate);//逾期利率
//            String marginamt = utilization_entity.getMarginamt();
//            test_entity.setMarginamt(marginamt + "00");//保证金
//            test_entity.setChgtype("1");//手续费类型
//            String chgdate = sdf.format(utilization_entity.getChgdate());
//            test_entity.setChgdate(chgdate);//手续费支付日
//            String chgamt = utilization_entity.getChgamt();
//            test_entity.setChgamt(chgamt + "00");//手续费总额
//            String paymentmethod = utilization_entity.getPaymentmethod();
//            test_entity.setPaymentmethod(paymentmethod);//还款方式
//            String ratetype = utilization_entity.getRatetype();
//            test_entity.setRatetype(ratetype);//利率类型
//            String firstpaydate = sdf.format(utilization_entity.getFirstpaydate());
//            test_entity.setFirstpaydate(firstpaydate);//首次还款日
//            test_entity.setSongkong("");//送空
//            test_entity.setPayper1("");//还款类型
//            test_entity.setJiaoyu("");//教育贷款优惠年数
//            test_entity.setLuru(userid);//录入用户
//            String lineccy = utilization_entity.getLineccy();
//            test_entity.setLineccy(lineccy);//额度币种
//            String spread = utilization_entity.getSpread();
//            test_entity.setSpread(spread);//利率调幅值
//            String percent = utilization_entity.getPercent();
//            test_entity.setRate(percent);//利率调幅百分比
//            String fixflag = utilization_entity.getFixflag();
//            test_entity.setFixflag(fixflag);//固定浮动标识
//            String payfreq = utilization_entity.getPayfreq();
//            test_entity.setPayfreq(payfreq);//还款周期频率
//            String payper = utilization_entity.getPayper();
//            test_entity.setPayper(payper);//还款周期
//            String duedate = sdf.format(utilization_entity.getDuedate());
//            test_entity.setDuedate(duedate);//还款到期日
//
//            String recieveMsg1 = null;
//            String prspcod1 = null;
//            JSONArray jsonArray = JSONArray.fromObject(test_entity);
//            JSONObject json = new JSONObject();
//            json.put("QCUSTCD", custcod);//客户号
//            json.put("QOVERWR", "Y");
//            json.put("QDITION", "");
//            json.put("QCNT", "0001");
//            json.put("QMSG", jsonArray.toString());
//            String message = ObjectHelp.InitTransferData("UtilizationdetailTx", json);
//            recieveMsg1 = client.transfer(message);
//            if (recieveMsg1 != null || recieveMsg1.length() > 0) {
//                System.out.println("开始处理返回信息");
//                JSONObject jsonObject = JSONObject.fromObject(recieveMsg1);
//                prspcod1 = jsonObject.getString("PRSPCOD");
//                result_C00005 = prspcod1;
//                if (prspcod1.equals("0000000")) {
//                    System.out.println("update UtilizationdetailInfo success");
//                } else {
//                    System.out.println("Cannot update UtilizationdetailInfo From Soa");
//                }
//                System.out.println("信息处理结束");
//            }
            result_C00005="0000000";
            //COOOO5 END
//            result_C00003="0000000";
//            result_C00004="0000";
//            result_C00005="0000000";
            //调用SOA接口成功，更新工作流
            if (result_C00003.equals("0000000") && result_C00004.equals("0000") && result_C00005.equals("0000000")) {
                WorkflowStub.KeyValueVariable[] req = {new WorkflowStub.KeyValueVariable(), new WorkflowStub.KeyValueVariable()};
                req[0].setVariableKey("Global.SECRESULT");
                req[0].setVariableValue("PASS");
                req[1].setVariableKey("Global.BranchMaxMoney");
                req[1].setVariableValue("PASS");
                String taskid = applyInfo_service.getWorkitemIdbyLoanid(loanid);
                String workstepId = workFlowServiceManager.getCurrentTaskStepId(taskid, userid);
                String result = workFlowServiceManager.UpdateWorkItem(userid, "role1", Integer.parseInt(workstepId), 1, 4, "OK", req);
                System.out.println("--------------"+result);
                JSONArray jsonArray1 = JSONArray.fromObject(result);
                JSONObject jsonObject = jsonArray1.getJSONObject(0);
                if (jsonObject.get("isSuc").equals("true")) {
                    //接口调用成功,根据custcod+lineno更新授权表额度loanapplicantfacilityinfo
                    //无数据，暂时写死
                    boolean state3 = applySerial_service.updateAmountWithBPM_NO("100", "100", "100", custcode, loanid);
                    examinationService.savaExamination(loanid, userid, examination);
                    //已保存
//                    applyInfo_service.applyInfoSubmit(userid, loanid, "审贷会审批", examination.getResult());
                    if (state3)
                        System.out.println("-----3完成-----");
                    else
                        System.out.println("-----3失败-----");


                }
            }
        } else if (examination.getResult().equals("4")) {
            //额度审批通过

            //此处判断tblusers. Businesamoun >= 本次授信中的额度金额
            //数据不全，暂不予判断，默认通过

            //根据custcode更新授信表AppFlag为Y
            String custcode = applySerial_service.getCustcodebyBPM_NO(loanid);
            if (custcode != null)
                applySerial_service.updateAppFlag(custcode);
        }


        model.addAttribute("branch", applyInfo_service.getBranch(userid));//登录用户所在银行
        model.addAttribute("puId", examinationService.getPuid(loanid));//自动生成的序号
        model.addAttribute("applyInfo_info", applyInfo_service.getPopupInfo(loanid));//申请工作流表
        model.addAttribute("users_info", examinationService.getUsersInfo());//参会委员获取
        model.addAttribute("examination", new Examination());//需要提交的审核结果表信息
        model.addAttribute("loanid", loanid);
        return "examination";
    }
}
